package com.example.im.ui.fragment

import android.content.Intent
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.common.Enumerate
import com.example.im.R
import com.example.im.common.ImApplication
import com.example.im.entity.EventBusData
import com.example.im.ui.adapter.FriendUserAdapter
import com.example.im.common.Constants
import com.example.im.entity.FriendOrRoom
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.ui.activity.UserActivity
import kotlinx.android.synthetic.main.fragment_friend_view_page.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jivesoftware.smack.roster.packet.RosterPacket

class FriendUserFragment : AbstractBaseFragment<BasePresenter<*>>(),
    FriendUserAdapter.OnClickItemListener {

    var friends = ArrayList<FriendOrRoom>()
    var adapter: FriendUserAdapter? = null

    override val layoutId: Int
        get() = R.layout.fragment_friend_view_page

    override fun initView() {

        EventBus.getDefault().register(this)

        val friendsDB = ImApplication.appDatabase()
            .friendOrRoomDao().selectFriends()
        friends.addAll(friendsDB)
        adapter = FriendUserAdapter(activity!!, friends)
        adapter!!.setOnItemClickListener(this)
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.adapter = adapter
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(eventBus: EventBusData<FriendOrRoom>) {
        if (eventBus.type == null ||
            eventBus.type != Enumerate.Handle.list_friend
        ) {
            return
        }
        val friend = eventBus.data
            ?: return
        when (eventBus.action ?: return) {
            Enumerate.Action.list_add ->
                adapter!!.addDataItem(friend)
            Enumerate.Action.list_delete ->
                adapter!!.removeDataItem(friend)
            else -> {
            }
        }
    }

    override fun onClickItem(view: View, position: Int) {
        val intent = Intent(activity, UserActivity::class.java)
        intent.putExtra(Constants.BUNDLE_T0_USER_DATA, friends[position])
        activity!!.startActivity(intent)
    }
}